package link

import "fmt"

type Node struct {
	data string
	Next *Node
}

func NewNode(data string) *Node {
	return &Node{
		data: data,
		Next: nil,
	}
}

func (n *Node) ShowNode() {
	fmt.Printf("[%s]", n.data)
}

func (n *Node) GetNext() *Node {
	return n.Next
}

func (n *Node) GetData() string {
	return n.data
}

type Link struct {
	Head *Node
	max  int
}

func NewLink(max int) *Link {
	return &Link{Head: NewNode(""), max: max}
}

func (l *Link) GetFirstNode() *Node {
	return l.Head.Next
}

func (l *Link) IsEmpty() bool {
	return l.Head.Next == nil
}

func (l *Link) IsFull() bool {
	return l.SizeOf() >= l.max
}

func (l *Link) Add(n *Node) {
	tmp := l.Head
	for tmp.Next != nil {
		tmp = tmp.Next
	}
	tmp.Next = n
}

func (l *Link) Del(data string) {
	tmp := l.Head
	for ; tmp.Next != nil; tmp = tmp.Next {
		if tmp.Next.data == data {
			tmp.Next = tmp.Next.Next
			break
		}
	}
}

func (l *Link) DelNode(n *Node) {
	tmp := l.Head
	for ; tmp.Next != nil; tmp = tmp.Next {
		if tmp.Next.data == n.data {
			tmp.Next = tmp.Next.Next
			break
		}
	}
}

func (l *Link) PopNode(n *Node) {
	tmp := l.Head
	var found bool
	for ; tmp.Next != nil; tmp = tmp.Next {
		if tmp.Next.data == n.data {
			tmp.Next = tmp.Next.Next
			found = true
			break
		}
	}
	if found {
		for tmp.Next != nil {
			tmp = tmp.Next
		}
		tmp.Next = n
		n.Next = nil
	}
}

func (l *Link) SizeOf() (n int) {
	tmp := l.Head
	for ; tmp.Next != nil; tmp = tmp.Next {
		n++
	}
	return
}

func (l *Link) FindNode(data string) (n *Node) {
	tmp := l.Head
	for ; tmp != nil; tmp = tmp.Next {
		if tmp.data == data {
			n = tmp
			return
		}
	}
	return
}

func (l *Link) ShowLink() {
	if l.IsEmpty() {
		return
	}
	// 打印的第一个节点应该是Head.Next
	for tmp := l.Head.Next; tmp != nil; tmp = tmp.Next {
		fmt.Printf("->")
		tmp.ShowNode()
	}
	fmt.Println()
}
